﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AgentExtractor.cs" company="Data Ductus Malmö">
//   (c) 2012 Data Ductus Malmö AB
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace DataDuctus.Snmp.EmbeddableNetSnmp.Internal
{
  using System;
  using System.IO;
  using System.Linq;

  using SharpCompress.Archive;
  using SharpCompress.Common;

  /// <summary>
  /// Extracts the snmp agent including mibs.
  /// </summary>
  internal sealed class AgentExtractor
  {
    #region Methods

    /// <summary>
    /// Extracts all mibs into <paramref name="toMibPath"/> folder.
    /// </summary>
    /// <param name="toMibPath">The folder to extract the mibs into.</param>
    internal static void ExtractMibs(string toMibPath)
    {
      using (
        var strm =
          typeof(AgentExtractor).Assembly.GetManifestResourceStream(
            "DataDuctus.Snmp.EmbeddableNetSnmp.Internal.mibs.7z"))
      {
        using (var archive = ArchiveFactory.Open(strm))
        {
          foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
          {
            entry.WriteToDirectory(toMibPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
          }
        }
      }
    }

    /// <summary>
    /// Extracts the snmpd.exe server into <paramref name="toBinPath"/>.
    /// </summary>
    /// <param name="toBinPath">
    /// The path to extract the server to.
    /// </param>
    /// <returns>
    /// The fully qualified path to the snmpd.exe file.
    /// </returns>
    internal static string ExtractServer(string toBinPath)
    {
      string arch = Environment.Is64BitOperatingSystem ? "x64" : "x86";

      using (
        var strm =
          typeof(AgentExtractor).Assembly.GetManifestResourceStream(
            string.Format("DataDuctus.Snmp.EmbeddableNetSnmp.Internal.{0}.7z", arch)))
      {
        using (var archive = ArchiveFactory.Open(strm))
        {
          foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
          {
            entry.WriteToDirectory(toBinPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
          }
        }
      }

      return Path.Combine(toBinPath, "snmpd.exe");
    }
    #endregion
  }
}
